package com.example.managementjava.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/Servlet_Stu")
public class Servlet_Stu extends HttpServlet {
    public static List<Student> Stulist = new ArrayList<>();
    private static Student student;
    public static List<Student> stulist = new ArrayList<>();
    private static int currentPage;
    @Override
    public void init(){
        Stulist = DB_Stu.selectAlllist();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //这里类型要设置未text/json
        resp.setContentType("text/json;charset=utf-8");
        PrintWriter out = resp.getWriter();

        out.println(Stulist.size());
        for (Student i : stulist){
            out.println(i.toString());
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8") ;
        currentPage = Integer.parseInt(req.getParameter("currentPage"));
        String searchMsg = req.getParameter("searchMsg");
        String way = req.getParameter("way");
        PrintWriter out = resp.getWriter();
        if(way.equals("all"))
            Stulist = DB_Stu.selectAlllist();
        else if(way.equals("search"))
            Stulist = DB_Stu.selectstudentlist(searchMsg);
        else if(way.equals("add")){
            DB_Stu.addStudent(searchMsg);
            Stulist = DB_Stu.selectAlllist();
        }
        else if(way.equals("edit")){
            DB_Stu.editStudent(searchMsg);
            Stulist = DB_Stu.selectAlllist();
        }
        else if(way.equals("del")){
            DB_Stu.delStudent(searchMsg);
            Stulist = DB_Stu.selectAlllist();
        }
        stulist = PagingData(currentPage);
    }

    private List<Student> PagingData(int currentPage) {
        List<Student> list = new ArrayList<>();
        currentPage-=1;
        int size = Stulist.size();
        int start = Math.max(currentPage * 10, 0);
        start = start>size?(size/10)*10:start;
        int end = Math.min(start + 10, size);
        if(end>size) end = size;
        for(int i =start;i<end;i++){
            list.add(Stulist.get(i));
        }
        return list;
    }
}
